<?php
use Phalcon\Di\FactoryDefault\Cli as CliDI;
use	Phalcon\Cli\Console as ConsoleApp;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Url;
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Config\Adapter\Ini as ConfigIni;

define('VERSION', '1.0.0');

// Using the CLI factory default services container
$di = new CliDI();

// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__)));

/**
 * Register the autoloader and tell it to register the tasks directory
 */
$config = new ConfigIni('app/config/config.ini');

$loader = new \Phalcon\Loader();
$loader->registerDirs(
	array(
		APPLICATION_PATH . '/tasks',
		$config->application->adaptersDir,
		$config->application->controllersDir,
		$config->application->formsDir,
		$config->application->modelsDir,
		$config->application->validatorsDir
	)
);
$loader->register();

// Database connection
$di->set('db', function () use ($config) {
	return new DbAdapter(
		array(
			"host"     => $config->database->host,
			"username" => $config->database->username,
			"password" => $config->database->password,
			"dbname"   => $config->database->name
		)
	);
});

// Create a console application
$console = new ConsoleApp();
$console->setDI($di);

/**
 * Process the console arguments
 */
$arguments = array();
foreach ($argv as $k => $arg) {
	if ($k == 1) {
		$arguments['task'] = $arg;
	} elseif ($k == 2) {
		$arguments['action'] = $arg;
	} elseif ($k >= 3) {
		$arguments['params'][] = $arg;
	}
}

// Define global constants for the current task and action
define('CURRENT_TASK',   (isset($argv[1]) ? $argv[1] : null));
define('CURRENT_ACTION', (isset($argv[2]) ? $argv[2] : null));

try {
	// Handle incoming arguments
	$console->handle($arguments);
} catch (\Phalcon\Exception $e) {
	echo $e->getMessage();
	exit(255);
}